package be.novelfaces.component.numpaddecsep;

import java.io.IOException;
import java.text.DecimalFormatSymbols;
import java.util.Locale;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;

import be.novelfaces.component.encoder.Encoder;
import be.novelfaces.util.StringUtils;

public class NumpadDecimalSeparatorJSEncoder implements Encoder {

	public void encode(FacesContext context, UIComponent component)
			throws IOException {
		ResponseWriter writer = context.getResponseWriter();
		writer.startElement("script", null);
		writer.writeAttribute("type", "text/javascript", null);
		writer.write("new NovelFaces.numpadDecSeparator('"
				+ component.getClientId() + "', {");
		writer.write("separator:'" + getSeparator(context, component) + "'");
		if(StringUtils.isNotEmpty((String) component.getAttributes().get("predefinedVariable"))) {
			writer.write(", predefinedVariables: " + component.getAttributes().get("predefinedVariable"));
		}
		writer.write("});");
		writer.endElement("script");
	}

	private String getSeparator(FacesContext context, UIComponent component) {
		if (StringUtils.isEmpty((String) component.getAttributes().get("separator"))
				|| component.getAttributes().get("separator") == "DEFAULT") {
			return getDecimalSeparatorFromLocaleFromViewRoot(context);
		}
		return (String) component.getAttributes().get("separator");
	}

	private String getDecimalSeparatorFromLocaleFromViewRoot(
			FacesContext context) {
		Locale locale = context.getViewRoot().getLocale();
		return String.valueOf(DecimalFormatSymbols.getInstance(locale)
				.getDecimalSeparator());
	}

}
